package com.timedomain.him.remake.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.VideoView;

import com.timedomain.him.remake.R;
import com.timedomain.him.remake.core.ChannelCreator;
import com.timedomain.him.remake.core.NightMode;
import com.timedomain.him.remake.core.SimplePlayer;
import com.timedomain.him.remake.service.PlayerService;
import com.timedomain.him.remake.utils.*;
import com.timedomain.him.remake.views.NumericUpAndDown;
import com.timedomain.him.remake.views.WaveformView;

import org.jetbrains.annotations.Nullable;

public class MainActivity extends BaseActivity {

    // region UI
    private LinearLayout mainActivityContainer;
    private FrameLayout mainActivityMainFrame;
    private Button btnEmergency;
    private Button btnMessage;
    private Button btnNightMode;
    private Button btnSettings;
    private VideoView videoMain;
    private View panelMainTop;
    private View panelMainBottom;

    private LinearLayout tblWelcomeMessage;
    private LinearLayout btnWelcomeMessage;
    private View panelMainMiddle;

    private void initUI(){	 mainActivityContainer = (LinearLayout)findViewById(R.id.mainActivityContainer);
        mainActivityMainFrame = (FrameLayout)findViewById(R.id.mainActivityMainFrame);
        btnEmergency = (Button)findViewById(R.id.btnEmergency);
        btnMessage = (Button)findViewById(R.id.btnMessage);
        btnNightMode = (Button)findViewById(R.id.btnNightMode);
        btnSettings = (Button)findViewById(R.id.btnSettings);
        videoMain = (VideoView)findViewById(R.id.videoMain);
        tblWelcomeMessage = findViewById(R.id.tblWelcomeMessage);
        btnWelcomeMessage = findViewById(R.id.btnWelcomeMessage);
        panelMainTop = findViewById(R.id.panelMainTop);
        panelMainBottom = findViewById(R.id.panelMainBottom);
        panelMainMiddle = findViewById(R.id.panelMainMiddle);
    }
    // endregion

    private SimplePlayer welcomeMessageVoice = null;

    public void closeWelcomeMessage(View view) {
        if(welcomeMessageVoice != null){
            welcomeMessageVoice.close();
        }
        welcomeMessageVoice = null;
        mainBgm.restart();
        AppSettings.hasSeenWelcomeMessage = true;
        AppSettings.saveSettings(this);
        tblWelcomeMessage.setVisibility(View.GONE);
        setTimerEnabled(true);
    }

    private void showWelcomeMessage(){
        tblWelcomeMessage.setVisibility(View.VISIBLE);
        tblWelcomeMessage.startAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
        btnWelcomeMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(welcomeMessageVoice != null){
                    welcomeMessageVoice.close();
                    welcomeMessageVoice = null;
                }
                welcomeMessageVoice = new SimplePlayer(ChannelCreator.FromFile(MainActivity.this, FileUtils.pathCombine("demo","stage3","message.ogg")));
                welcomeMessageVoice.start();
            }
        });
        setTimerEnabled(false);
    }



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(AppSettings.firstRun){
            finish();
            return;
        }
        setContentView(R.layout.activity_main);
        initUI();
        initVideo();
        initAudio();
        MorningCallManager.setNextMorningCall(this);
        SpecialEventManager.checkHasSpecialEvent(this);

        setTimerInterval(1000);
        setTimerEnabled(true);

        if(!AppSettings.hasSeenWelcomeMessage){
            mainBgm.pause();
            showWelcomeMessage();
        }


        panelMainMiddle.setOnClickListener(this::clearAnimation);
    }

    private boolean isVideoPrepared = false;

    private void initVideo(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            videoMain.setAudioFocusRequest(AudioManager.AUDIOFOCUS_NONE);
        }

        videoMain.setVideoURI(Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.him_wennuan));
        videoMain.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setVolume(0,0);
                mp.setLooping(true);
                videoMain.start();
                isVideoPrepared = true;
            }
        });

    }

    SimplePlayer mainBgm = null;

    private void initAudio(){
        mainBgm = new SimplePlayer(ChannelCreator.FromAsset(getAssets(),"audio/him_bgm.ogg"));
        mainBgm.setLooping(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoMain.pause();
        mainBgm.pause();
    }

    private int fadeoutTimeout = 15;

    @Override
    protected void onTimer() {
        if(fadeoutTimeout > 0){
            fadeoutTimeout --;
        }
        else{
            if(fadeoutTimeout == 0){
                fadeoutTimeout = -1;
                Animation anim = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
                anim.setFillAfter(true);
                anim.setDuration(3000);
                panelMainTop.startAnimation(anim);
                anim = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
                anim.setFillAfter(true);
                anim.setDuration(3000);
                panelMainBottom.startAnimation(anim);
            }
        }
    }

    private void clearAnimation(View v){
        if(fadeoutTimeout > 0){
            fadeoutTimeout = 15;
        }
        else{
            fadeoutTimeout = 15;
            panelMainBottom.clearAnimation();
            panelMainTop.clearAnimation();
            Animation anim = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
            anim.setFillAfter(true);
            anim.setDuration(333);
            panelMainTop.startAnimation(anim);
            anim = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
            anim.setFillAfter(true);
            anim.setDuration(333);
            panelMainBottom.startAnimation(anim);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(AppSettings.firstRun){
            finish();
            return;
        }
        fadeoutTimeout = 15;
        panelMainBottom.clearAnimation();
        panelMainTop.clearAnimation();
        if(isVideoPrepared){
            videoMain.start();
        }
        if(tblWelcomeMessage.getVisibility() == View.VISIBLE){
            return;
        }
        if(PlayerService.player == null){
            mainBgm.restart();
        }
        if(!AppSettings.hasSeenBatteryOptimizationDialog){
            setTimeout(()->{
                new AlertDialog.Builder(this).setTitle("后台白名单")
                        .setMessage("要将时空通讯器添加到后台白名单吗？")
                        .setPositiveButton("打开设置", (dialog, which) -> startActivity(new Intent(MainActivity.this,BackgroundActivateSettingsActivity.class))).setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AppSettings.hasSeenBatteryOptimizationDialog = true;
                        AppSettings.saveSettings(MainActivity.this);
                        showToast("稍后也可以在设置中找到此页面。");
                    }
                }).setCancelable(false).create().show();
            },200);

        } else if(!AppSettings.hasSeenNotificationDialog){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                setTimeout(()->{
                    new AlertDialog.Builder(this).setTitle("通知权限")
                            .setMessage("当前系统版本需要手动打开通知权限，是否进行设置？")
                            .setPositiveButton("打开设置", (dialog, which) -> {
                                AppSettings.hasSeenNotificationDialog = true;

                                AppSettings.saveSettings(MainActivity.this);
                                NotificationUtils.showNotificationSetting(this);
                            }).setNegativeButton("以后再说", (dialog, which) -> {
                                AppSettings.hasSeenNotificationDialog = true;
                                AppSettings.saveSettings(MainActivity.this);
                                showToast("稍后也可以在设置中找到此页面。");
                            }).setCancelable(false).create().show();
                },200);
            }

        }
        if(AppSettings.readedChatMessageTime == -1){
            AppSettings.readedChatMessageTime = TimeUtils.getTimeStampIgnoreTimeZone();
        }
        boolean hasUnreaded = AppSettings.lastChatMessageTime > AppSettings.readedChatMessageTime;
        findViewById(R.id.viewUnreadIndicator).setVisibility(hasUnreaded ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onBackPressed() {
        if(fadeoutTimeout <= 0){
            clearAnimation(null);
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoMain.suspend();
        mainBgm.close();
    }

    @Override
    protected void onUiPrepared() {
        super.onUiPrepared();
        int w = mainActivityContainer.getWidth();
        int h = mainActivityContainer.getHeight();

        int allMargins = 0;

        if(h * 9 / 16 > w){ // 全面屏
            int th = w * 16 / 9;
            allMargins = h - th;
            h = th;
        }
        else{
            w = h * 9 / 16;
        }

        int topmargin = allMargins / 4;
        int bottommargin = allMargins / 4 * 3;

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mainActivityMainFrame.getLayoutParams();
        lp.width = w;
        lp.height = h;
        lp.topMargin = topmargin;
        lp.bottomMargin = bottommargin;
        mainActivityMainFrame.setLayoutParams(lp);
    }
    Handler handler = new Handler();
    public void buttonsClick(View view) {

        int id = view.getId();
        if(id == R.id.btnEmergency){
            startActivity(new Intent(this,EmergencyVoiceActivity.class));
        }else if(id == R.id.btnSettings){
            startActivity(new Intent(this,SettingActivity.class));
        }else if(id == R.id.btnMessage){
            startActivity(new Intent(this,MessageActivity.class));
        }else if(id == R.id.btnNightMode){
            NightActivity.startNightMode(this);

        }else if(id == R.id.btnMorningCall){
            startActivity(new Intent(this,MorningCallActivity.class));
        }
    }

}
